<template>
  <div class="real-time-prediction-page">
    <!-- 通用导航栏 -->
    <CommonNavBar pageTitle="实时预测" />
    
    <!-- 动态电流背景 -->
    <div class="electric-background">
      <div class="electric-line horizontal" v-for="i in 8" :key="'h' + i" :style="{ top: (i * 12.5) + '%', animationDelay: (i * 0.2) + 's' }"></div>
      <div class="electric-line vertical" v-for="i in 12" :key="'v' + i" :style="{ left: (i * 8.33) + '%', animationDelay: (i * 0.15) + 's' }"></div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="page-content">
      <div class="module-container">
        <h2>实时预测管理</h2>
        <p>实时获取最新数据并进行短期负荷预测</p>
        
        <!-- 预测控制面板 -->
        <div class="prediction-panel">
          <div class="prediction-controls">
            <h3>预测控制</h3>
            
            <!-- 日期选择 -->
            <!-- <div class="date-selector">
              <label>选择预测日期:</label>
              <select v-model="selectedDate" @change="onDateChange">
                <option v-for="date in futureDates" :key="date.date" :value="date.date">
                  {{ date.display_name }} ({{ date.formatted }})
                </option>
              </select>
            </div> -->
            
            <!-- 模型选择 -->
            <div class="model-selector">
              <label>选择预测模型:</label>
              <select v-model="selectedModel" @change="onModelChange">
                <option value="">自动推荐最优模型</option>
                <option v-for="model in availableModels" :key="model" :value="model">
                  {{ model.toUpperCase() }}
                </option>
              </select>
            </div>
            
            <div class="control-buttons">
              <button class="predict-btn" @click="startPrediction" :disabled="isPredicting">
                <Icon type="ios-flash" size="16" />
                {{ isPredicting ? '预测中...' : '开始预测' }}
              </button>
              <button class="refresh-btn" @click="refreshData">
                <Icon type="ios-refresh" size="16" />
                刷新数据
              </button>
            </div>
          </div>
          
          <div class="prediction-status">
            <h3>预测状态</h3>
            <div class="status-grid">
              <div class="status-item">
                <span class="status-label">数据同步：</span>
                <span class="status-value" :class="{ 'success': dataStatus.synced }">
                  {{ dataStatus.synced ? '已同步' : '未同步' }}
                </span>
              </div>
              <div class="status-item">
                <span class="status-label">模型就绪：</span>
                <span class="status-value" :class="{ 'success': modelStatus.ready }">
                  {{ modelStatus.ready ? '已就绪' : '未就绪' }}
                </span>
              </div>
              <div class="status-item">
                <span class="status-label">预测结果：</span>
                <span class="status-value" :class="{ 'success': predictionStatus.completed }">
                  {{ predictionStatus.completed ? '已完成' : '未完成' }}
                </span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 预测结果展示 -->
        <div class="prediction-results" v-if="predictionData">
          <h3>预测结果</h3>
          
          <!-- 天气信息 -->
          <div class="weather-info" v-if="predictionData.weather_info">
            <h4>当天气象信息</h4>
            <div class="weather-container">
              <div class="weather-item">
                <span class="weather-icon">🌡️</span>
                <span class="weather-label">温度:</span>
                <span class="weather-value">
                  {{ predictionData.weather_info.temperature.min }}°C - {{ predictionData.weather_info.temperature.max }}°C
                </span>
              </div>
              <div class="weather-item">
                <span class="weather-icon">💧</span>
                <span class="weather-label">降水:</span>
                <span class="weather-value">{{ predictionData.weather_info.precipitation }} mm</span>
              </div>
              <div class="weather-item">
                <span class="weather-icon">💨</span>
                <span class="weather-label">湿度:</span>
                <span class="weather-value">{{ predictionData.weather_info.humidity || 'N/A' }}%</span>
              </div>
              <div class="weather-item">
                <span class="weather-icon">☀️</span>
                <span class="weather-label">天气:</span>
                <span class="weather-value">{{ predictionData.weather_info.conditions }}</span>
              </div>
            </div>
          </div>
          
          <!-- 96点预测曲线图 -->
          <div class="prediction-chart" v-if="predictionData.prediction_values">
            <h4>96点预测电荷曲线</h4>
            <div ref="predictionChart" class="chart-container"></div>
          </div>
          
          <!-- 预测统计信息 -->
          <div class="prediction-stats">
            <div class="stat-item">
              <span class="stat-label">峰值负荷:</span>
              <span class="stat-value">{{ predictionData.peak_load?.toFixed(2) }} MW</span>
              <span class="stat-time">({{ predictionData.peak_time }})</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">谷值负荷:</span>
              <span class="stat-value">{{ predictionData.valley_load?.toFixed(2) }} MW</span>
              <span class="stat-time">({{ predictionData.valley_time }})</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">平均负荷:</span>
              <span class="stat-value">{{ predictionData.avg_load?.toFixed(2) }} MW</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">预测精度:</span>
              <span class="stat-value">{{ (predictionData.accuracy * 100)?.toFixed(1) }}%</span>
            </div>
          </div>
          
          <!-- 特征重要性分析 -->
          <div class="feature-analysis" v-if="predictionData.feature_importance_data">
            <FeatureImportanceComparison :featureData="predictionData.feature_importance_data" />
            <ModelWeightAndCategoryChart :featureData="predictionData.feature_importance_data" />
          </div>
        </div>
        
        <!-- 预测日志 -->
        <div class="prediction-log">
          <h3>预测日志</h3>
          <div class="log-container">
            <div v-for="(log, index) in predictionLogs" :key="index" class="log-item" :class="log.type">
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CommonNavBar from '@/components/CommonNavBar'
import FeatureImportanceComparison from '@/components/prediction/FeatureImportanceComparison'
import ModelWeightAndCategoryChart from '@/components/prediction/ModelWeightAndCategoryChart'

export default {
  name: 'RealTimePredictionPage',
  components: {
    CommonNavBar,
    FeatureImportanceComparison,
    ModelWeightAndCategoryChart
  },
  data() {
    return {
      isPredicting: false,
      selectedDate: '',
      selectedModel: '',
      futureDates: [],
      availableModels: [],
      dataStatus: {
        synced: false
      },
      modelStatus: {
        ready: false
      },
      predictionStatus: {
        completed: false
      },
      predictionData: null,
      predictionLogs: []
    }
  },
  mounted() {
    this.initPage()
  },
  methods: {
    async initPage() {
      console.log('实时预测页面加载完成')
      await this.loadFutureDates()
      await this.loadAvailableModels()
      this.checkSystemStatus()
    },
    async checkSystemStatus() {
      try {
        // 这里可以调用API检查系统状态
        // const response = await this.$api.getSystemStatus()
        
        // 暂时使用模拟数据
        this.dataStatus.synced = true
        this.modelStatus.ready = true
      } catch (error) {
        console.error('检查系统状态失败:', error)
      }
    },
    async startPrediction() {
      if (this.isPredicting) return
      
      this.isPredicting = true
      this.addLog('info', '开始实时预测...')
      
      try {
        if (!this.selectedDate) {
          this.addLog('error', '请先选择预测日期')
          this.isPredicting = false
          return
        }
        
        this.addLog('success', '数据预处理完成')
        
        // 使用今天的日期进行预测
        const today = new Date().toISOString().split('T')[0]
        
        // 调用单日预测API
        const config = {
          target_date: today,
          model: this.selectedModel || 'lightgbm'
        }
        
        const response = await this.$api.get(`/prediction/single-day-prediction?target_date=${config.target_date}&model=${config.model}`)
        
        if (response.success) {
          this.predictionData = response.data
          this.predictionStatus.completed = true
          this.addLog('success', '模型预测完成')
          
          // 绘制预测曲线图
          this.$nextTick(() => {
            this.drawPredictionChart()
          })
          
          this.addLog('success', '预测结果已生成')
        } else {
          this.addLog('error', '预测失败: ' + (response.message || '未知错误'))
        }
        
        this.isPredicting = false
        
      } catch (error) {
        this.addLog('error', '预测失败: ' + error.message)
        this.isPredicting = false
      }
    },
    async refreshData() {
      this.addLog('info', '刷新数据...')
      await this.checkSystemStatus()
      this.addLog('success', '数据刷新完成')
    },
    async loadFutureDates() {
      try {
        const response = await this.$api.get('/prediction/future-dates')
        if (response.success) {
          this.futureDates = response.data
          // 默认选择今天，如果没有今天的数据则选择第一个可用日期
          const today = new Date()
          const todayStr = today.toISOString().split('T')[0]
          const todayOption = this.futureDates.find(date => date.date === todayStr)
          this.selectedDate = todayOption ? todayOption.date : (this.futureDates[0]?.date || '')
        }
      } catch (error) {
        console.error('加载未来日期失败:', error)
        this.addLog('error', '加载未来日期失败')
        // 如果API失败，设置今天为默认日期
        const today = new Date()
        this.selectedDate = today.toISOString().split('T')[0]
      }
    },
    async loadAvailableModels() {
      try {
        const response = await this.$api.get('/prediction/models')
        if (response.success) {
          this.availableModels = response.data
        }
      } catch (error) {
        console.error('加载模型列表失败:', error)
        this.addLog('error', '加载模型列表失败')
      }
    },
    onDateChange() {
      this.addLog('info', `选择预测日期: ${this.selectedDate}`)
    },
    onModelChange() {
      if (this.selectedModel) {
        this.addLog('info', `选择预测模型: ${this.selectedModel}`)
      } else {
        this.addLog('info', '选择自动推荐最优模型')
      }
    },
    drawPredictionChart() {
      if (!this.predictionData || !this.predictionData.prediction_values) {
        return
      }
      
      const chartDom = this.$refs.predictionChart
      if (!chartDom) {
        return
      }
      
      // 简单的SVG图表实现
      const data = this.predictionData.prediction_values
      const labels = this.predictionData.time_labels
      
      const width = chartDom.clientWidth || 800
      const height = 300
      const margin = { top: 20, right: 30, bottom: 40, left: 60 }
      
      const maxValue = Math.max(...data)
      const minValue = Math.min(...data)
      const range = maxValue - minValue
      
      let svg = `<svg width="${width}" height="${height}" style="background: rgba(7, 19, 50, 0.4); border-radius: 8px;">
        <defs>
          <linearGradient id="lineGradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" style="stop-color:#75deef;stop-opacity:0.8" />
            <stop offset="100%" style="stop-color:#75deef;stop-opacity:0.1" />
          </linearGradient>
        </defs>`
      
      // 绘制网格线
      for (let i = 0; i <= 5; i++) {
        const y = margin.top + (height - margin.top - margin.bottom) * i / 5
        svg += `<line x1="${margin.left}" y1="${y}" x2="${width - margin.right}" y2="${y}" stroke="rgba(255,255,255,0.1)" stroke-width="1"/>`
        
        const value = maxValue - (range * i / 5)
        svg += `<text x="${margin.left - 10}" y="${y + 5}" fill="#999" font-size="10" text-anchor="end">${value.toFixed(0)}</text>`
      }
      
      // 绘制曲线
      let pathData = ''
      for (let i = 0; i < data.length; i++) {
        const x = margin.left + (width - margin.left - margin.right) * i / (data.length - 1)
        const y = margin.top + (height - margin.top - margin.bottom) * (1 - (data[i] - minValue) / range)
        
        if (i === 0) {
          pathData += `M ${x} ${y}`
        } else {
          pathData += ` L ${x} ${y}`
        }
        
        // 显示每6个点的时间标签（每1.5小时）
        if (i % 6 === 0) {
          svg += `<text x="${x}" y="${height - 5}" fill="#999" font-size="10" text-anchor="middle">${labels[i]}</text>`
        }
      }
      
      svg += `<path d="${pathData}" stroke="#75deef" stroke-width="2" fill="none"/>`
      svg += `<path d="${pathData} L ${width - margin.right} ${height - margin.bottom} L ${margin.left} ${height - margin.bottom} Z" fill="url(#lineGradient)"/>`
      
      // 标题
      svg += `<text x="${width/2}" y="15" fill="#75deef" font-size="14" text-anchor="middle" font-weight="bold">电荷负荷预测曲线 (MW)</text>`
      
      svg += '</svg>'
      
      chartDom.innerHTML = svg
    },
    addLog(type, message) {
      const time = new Date().toLocaleTimeString()
      this.predictionLogs.push({
        type,
        time,
        message
      })
      
      // 保持日志数量在合理范围内
      if (this.predictionLogs.length > 50) {
        this.predictionLogs = this.predictionLogs.slice(-50)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.real-time-prediction-page {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #0c1426 0%, #1a2332 50%, #0f1b2a 100%);
  padding: 20px;
  padding-top: 100px; // 为导航栏留出空间
  box-sizing: border-box;
  position: relative;
  
  // 动态电流背景
  .electric-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0.3;
    z-index: 1;
    
    .electric-line {
      position: absolute;
      background: linear-gradient(90deg, transparent, #ffd93d, transparent);
      box-shadow: 0 0 10px #ffd93d;
      
      &.horizontal {
        width: 100%;
        height: 2px;
        animation: electricFlowH 3s ease-in-out infinite;
      }
      
      &.vertical {
        width: 2px;
        height: 100%;
        animation: electricFlowV 4s ease-in-out infinite;
      }
    }
  }
  
  .page-content {
    position: relative;
    z-index: 10;
    margin-bottom: 20px;
    
    .module-container {
      width: 100%;
      background: rgba(7, 19, 50, 0.6);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 30px;
      position: relative;
      backdrop-filter: blur(10px);
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(90deg, #ffd93d, #ffb347);
        border-radius: 12px 12px 0 0;
      }
      
      h2 {
        color: #75deef;
        font-size: 24px;
        margin-bottom: 10px;
      }
      
      p {
        color: #999;
        font-size: 16px;
        margin-bottom: 30px;
      }
      
      .prediction-panel {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 30px;
        margin-bottom: 30px;
        
        .prediction-controls, .prediction-status {
          background: rgba(7, 19, 50, 0.4);
          border: 1px solid #1a3c58;
          border-radius: 8px;
          padding: 20px;
          
          h3 {
            color: #75deef;
            font-size: 18px;
            margin-bottom: 15px;
          }
          
          .date-selector, .model-selector {
            margin-bottom: 15px;
            position: relative;
            z-index: 100;
            
            label {
              display: block;
              color: #75deef;
              font-size: 14px;
              margin-bottom: 5px;
            }
            
            select {
              width: 100%;
              padding: 8px 12px;
              background: rgba(7, 19, 50, 0.4);
              border: 1px solid #1a3c58;
              border-radius: 6px;
              color: #fff;
              font-size: 14px;
              position: relative;
              z-index: 1000;
              
              option {
                background: #0c1426;
                color: #fff;
              }
              
              &:focus {
                outline: none;
                border-color: #75deef;
                box-shadow: 0 0 5px rgba(117, 222, 239, 0.3);
                z-index: 1001;
              }
            }
          }
          
          .control-buttons {
            display: flex;
            gap: 10px;
            
            button {
              display: flex;
              align-items: center;
              gap: 5px;
              padding: 10px 20px;
              border: none;
              border-radius: 6px;
              cursor: pointer;
              font-size: 14px;
              transition: all 0.3s ease;
              
              &.predict-btn {
                background: rgba(255, 217, 61, 0.2);
                color: #ffd93d;
                border: 1px solid #ffd93d;
                
                &:hover:not(:disabled) {
                  background: rgba(255, 217, 61, 0.3);
                }
                
                &:disabled {
                  opacity: 0.6;
                  cursor: not-allowed;
                }
              }
              
              &.refresh-btn {
                background: rgba(78, 205, 196, 0.2);
                color: #4ecdc4;
                border: 1px solid #4ecdc4;
                
                &:hover {
                  background: rgba(78, 205, 196, 0.3);
                }
              }
            }
          }
          
          .status-grid {
            display: grid;
            gap: 10px;
            
            .status-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 8px 12px;
              background: rgba(7, 19, 50, 0.3);
              border-radius: 6px;
              
              .status-label {
                color: #999;
                font-size: 14px;
              }
              
              .status-value {
                color: #ff6b6b;
                font-size: 14px;
                font-weight: bold;
                
                &.success {
                  color: #4ecdc4;
                }
              }
            }
          }
        }
      }
      
      .prediction-results {
        margin-bottom: 30px;
        
        h3, h4 {
          color: #75deef;
          font-size: 18px;
          margin-bottom: 15px;
        }
        
        h4 {
          font-size: 16px;
          margin-top: 20px;
        }
        
        .weather-info {
          background: rgba(7, 19, 50, 0.4);
          border: 1px solid #1a3c58;
          border-radius: 8px;
          padding: 20px;
          margin-bottom: 20px;
          
          .weather-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            
            .weather-item {
              display: flex;
              align-items: center;
              gap: 8px;
              padding: 10px;
              background: rgba(7, 19, 50, 0.3);
              border-radius: 6px;
              
              .weather-icon {
                font-size: 16px;
              }
              
              .weather-label {
                color: #999;
                font-size: 14px;
              }
              
              .weather-value {
                color: #4ecdc4;
                font-weight: bold;
                font-size: 14px;
              }
            }
          }
        }
        
        .prediction-chart {
          background: rgba(7, 19, 50, 0.4);
          border: 1px solid #1a3c58;
          border-radius: 8px;
          padding: 20px;
          margin-bottom: 20px;
          
          .chart-container {
            width: 100%;
            height: 300px;
            margin-top: 10px;
          }
        }
        
        .prediction-stats {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          gap: 15px;
          
          .stat-item {
            background: rgba(7, 19, 50, 0.4);
            border: 1px solid #1a3c58;
            border-radius: 8px;
            padding: 15px;
            display: flex;
            flex-direction: column;
            gap: 5px;
            
            .stat-label {
              color: #999;
              font-size: 14px;
            }
            
            .stat-value {
              color: #4ecdc4;
              font-size: 18px;
              font-weight: bold;
            }
            
            .stat-time {
              color: #75deef;
              font-size: 12px;
              font-style: italic;
            }
          }
        }
      }
      
      .prediction-log {
        h3 {
          color: #75deef;
          font-size: 18px;
          margin-bottom: 15px;
        }
        
        .log-container {
          background: rgba(7, 19, 50, 0.4);
          border: 1px solid #1a3c58;
          border-radius: 8px;
          padding: 15px;
          max-height: 300px;
          overflow-y: auto;
          
          .log-item {
            display: flex;
            gap: 10px;
            margin-bottom: 8px;
            padding: 5px 0;
            
            .log-time {
              color: #666;
              font-size: 12px;
              min-width: 80px;
            }
            
            .log-message {
              color: #999;
              font-size: 14px;
            }
            
            &.success .log-message {
              color: #4ecdc4;
            }
            
            &.error .log-message {
              color: #ff6b6b;
            }
            
            &.info .log-message {
              color: #75deef;
            }
          }
        }
      }
    }
  }
}

// 电流流动动画
@keyframes electricFlowH {
  0% {
    transform: translateX(-100%);
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    transform: translateX(100%);
    opacity: 0;
  }
}

@keyframes electricFlowV {
  0% {
    transform: translateY(-100%);
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    transform: translateY(100%);
    opacity: 0;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .real-time-prediction-page {
    padding-top: 90px;
    
    .page-content .module-container .prediction-panel {
      grid-template-columns: 1fr;
      gap: 20px;
    }
  }
}

@media (max-width: 768px) {
  .real-time-prediction-page {
    padding: 15px;
    padding-top: 80px;
    
    .page-content .module-container {
      padding: 20px;
      
      .prediction-panel {
        .control-buttons {
          flex-direction: column;
        }
      }
      
      .prediction-results .results-container {
        grid-template-columns: 1fr;
      }
    }
  }
}
</style> 